import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/Refresher.dart';
import 'package:huajianshe_app/common/C.dart';
import 'package:huajianshe_app/common/TS.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/pages/circle/model/CircleModel.dart';
import 'package:huajianshe_app/pages/main/model/MomentModel.dart';
import 'package:huajianshe_app/utils/Device.dart';
import 'package:huajianshe_app/utils/KeyboardUtil.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:oktoast/oktoast.dart';
import 'CommentItem.dart';
import 'MomentItem.dart';
import 'model/CommentModel.dart';

class MomentDetailPage extends StatefulWidget {

  // final String? aimId;
  final MomentListData? momentListData;
  final CircleInfo? circleInfo;

  const MomentDetailPage(this.momentListData, this.circleInfo, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MomentDetailPageState();
  }
}

class MomentDetailPageState extends BaseState<MomentDetailPage> {

  bool keyboardShown = false;
  bool showButton = false;
  TextEditingController editingController = TextEditingController();
  FocusNode inputNode = FocusNode();
  CommentListDataWithPageInfo? dataWithPageInfo;
  int page = 1;

  @override
  void initState() {
    super.initState();
    refresher = Refresher<CommentListData>(this);
    load(false);
  }

  void load(bool doNotShowProgressBar) {
    var data = {
      'page': page,
      'list_rows': 10,
      'aim_id': widget.momentListData?.id,
      'aim_type': 1 //1动态，3课程
    };
    sendReq(Api.commentList(), CommentListResp(), data: data, doNotShowProgressBar: doNotShowProgressBar);
  }

  @override
  void onRefresh() {
    super.onRefresh();
    refresher?.mode = Mode.refresh;
    page = 1;
    load(true);
  }

  @override
  void onLoadMore() {
    super.onLoadMore();
    refresher?.mode = Mode.loadMore;
    load(true);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    super.onReqSuccess(t, code, msg, path);
    if (t is CommentListResp) {
      dataWithPageInfo = t.data;
      List<CommentListData>? data = dataWithPageInfo?.data;
      refresher?.load(data);
      widget.momentListData?.commentNum = dataWithPageInfo?.total; // 同步评论数
      setState(() { });
      page++;
    } else if (t is CommentResp) {
      showToast(t.msg ?? '');
      refresher?.insert2First(t.data);
      editingController.text = '';
      int commentNum = dataWithPageInfo?.total == null ? 1 : dataWithPageInfo!.total! + 1;
      dataWithPageInfo?.total = commentNum;
      widget.momentListData?.commentNum = commentNum;
      setState(() => null);
    }
  }

  void doComment(String? text) {
    if (text?.isNotEmpty == true) {
      var data = {
        'aim_type': 1,
        'aim_id': widget.momentListData?.id,
        'content': text
      };
      sendReq(Api.doComment(), CommentResp(), data: data, doNotShowProgressBar: false);
    }
  }

  @override
  Widget build(BuildContext context) {
    keyboardShown = KeyboardUtil.isKeyboardShown(context);
    // if (!keyboardShown) showButton = false;
    return
      Scaffold(
      backgroundColor: Colors.transparent,
        body:
        Container(
          child: Column(children: [
            SizedBox(height: 45, child: Row(children: [
              W(15),
              Text('动态详情', style: TS(15, C.gray1A)),
              Spacer(),
              SmartButton(width: 20, height: 20, drawableLeft: LoadImage('ic_close'), backgroundColor: Colors.transparent, borderColor: Colors.transparent,
                  onPressed: () { AppNavigator.pop(context); }),
              W(15)
            ])),
            D(),
            Expanded(child: refresher!.build(buildChild())),
            // if (showButton)
            buildBottom()
          ]),
        )

    );

  }

  Widget buildChild() {
    // Widget? child = buildEmptyPage();
    // if (child != null) {
    //   return child;
    // }
    return
    ListView.separated(
        itemBuilder: (_, index) {
          if (index == 0) {
            return Column(mainAxisSize: MainAxisSize.min, children: [
              MomentItem(widget.momentListData ?? MomentListData(), widget.circleInfo, onComment: onComment),
              DD(),
              H(15),
              Row(children: [
                W(15),
                Text('评论 (共${dataWithPageInfo?.total ?? 0}条)', style: TS(15, C.gray1A),)
              ])
            ]);
          } else {
            return Padding(padding: EdgeInsets.all(15), child: CommentItem(refresher?.data?[index - 1], null)); //todo 评论列表里进去的都是好友
          }
        },
        separatorBuilder: (_, index) {
          if (index > 0) {
            return PD(1, 63, 0);
          }
          return H(0);
        },
        itemCount: (refresher?.data?.length ?? 0) + 1
    );
  }

  Widget buildBottom() {
    return Container(color: C.grayF6, padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), child: Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        Expanded(child: TextField(
          autofocus: false,
          controller: editingController,
          focusNode: inputNode,
          textInputAction: TextInputAction.send,
          onSubmitted: (value) {
            print('submit $value');
            doComment(value);
          },
          decoration: InputDecoration(
            isDense: true,
            contentPadding: EdgeInsets.only(
              left: 10, right: 10, top: 5, bottom: 5),
              fillColor: Colors.white,
              filled: true,
              border: new OutlineInputBorder(
                borderSide: BorderSide.none,
                borderRadius: const BorderRadius.all(
                  const Radius.circular(3.0),
                ),
              ),
            hintStyle: TextStyle(color: Color(0xffcccccc)),
            hintText: "说点什么吧"),
        )),
        if (keyboardShown && Device.isIOS)
          GestureDetector(onTap: () {FocusScope.of(context).unfocus();}, child: Icon(Icons.arrow_drop_down)),
        // TextButton(onPressed: null, child: Text('发布'))
      ],
    ),);
  }

  void onComment(MomentListData? data) {
    FocusScope.of(context).requestFocus(inputNode);
  }
}